package fr.sedoo.rbv.geonetwork.request;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import fr.sedoo.commons.metadata.utils.domain.Summary;
import fr.sedoo.rbv.geonetwork.config.GeonetworkConfig;
import fr.sedoo.rbv.geonetwork.domain.GeonetworkUser;

public class MyMetadataDeleteAllRequest extends AuthenticatedRequest 
{
	public MyMetadataDeleteAllRequest(GeonetworkConfig config)
	{
		super(config);
	}

	public MyMetadataDeleteAllRequest(GeonetworkUser user)
	{
		super(user);

	}

	public MyMetadataDeleteAllRequest()
	{
		super();

	}

	public boolean execute() throws Exception
	{
		
		MySummaryRequest mySummaryRequest = new MySummaryRequest(getUser());
		List<String> deletedIdentifiers = new ArrayList<String>();
		boolean result = mySummaryRequest.execute();
		if (result == true)
		{
			List<Summary> summaries = mySummaryRequest.getSummaries();
			Iterator<Summary> iterator = summaries.iterator();
			while (iterator.hasNext()) 
			{
				Summary summary = (Summary) iterator.next();
				String uuid = summary.getUuid();
				MetadataDeleteRequest request = new MetadataDeleteRequest(uuid);
				try 
				{
					boolean isDeleted = request.execute();
					if (isDeleted)
					{
						deletedIdentifiers.add(uuid);
					}
					else
					{
						throw new Exception("The deletion request has returned false.");
					}
				}
				catch (Exception e)
				{
					throw new Exception("An exception has occured. Only few entries has been deleted ("+getValues(deletedIdentifiers)+"). "+e.getMessage());
				}
			}
			return true;
		}
		else
		{
			throw new Exception("Unable to list the metadatas");
		}
	}
	
	private String getValues(List<String> list)
	{
		String separator=",";
		Iterator<String> iterator = list.iterator();
		StringBuilder sb = new StringBuilder();
		while (iterator.hasNext()) 
		{
			sb.append(iterator.next());
			if (iterator.hasNext())
			{
				sb.append(separator);
			}
		}
		return sb.toString();
	}
}
